
#ifndef __STREAM_TO_DIRECTORY_H
#define __STREAM_TO_DIRECTORY_H

#include <vector>
#include <stack>
#include <stdint.h>
#include <apr_pools.h>
#include <apr_thread_proc.h>
#include "../db/NewKeyDB.h"

/** Takes the serialised contents of a directory and rebuilds the
 * directory from it. */
class StreamToDirectory
{
   public:
      /** Stream section flag. */
      enum currflagtype {   READING_FILE_NAME_SIZE   = 0,
                            READING_FILE_STREAM_SIZE = 1,
                            READING_NAME             = 2,
                            READING_STREAM           = 3   };
      StreamToDirectory(const char *directorypath, apr_pool_t *imp);
      ~StreamToDirectory();
      static int64_t readLogical64Bit(unsigned char *bytes);
      void putNextBlock(char *blockbuffer, apr_off_t *tsize);
      int PutNextBlockDecrypted(const char *cname, KeyPair *kp, const char *realbuffer, int *realsize, int *cesize, char **hash);
      int PutNextBlockDecrypted(const char *decwith, KeyDB *kdb, const char *realbuffer, int *realsize, int *cesize, char **hash);
      int recreateFile(char *blockbuffer, apr_off_t *maxlen);
   private:
      /** APR memory pool to use for this instance. */
      apr_pool_t *mp;
      /** Directory into which the reconstruction is to occur. */
      char *directory_name;
      /** A flag indicating the current section of the stream under reconstruction. */
      int currflag;
      /** The number of bytes of the current section of the stream that have
       * already been read. */
      int64_t currbytesthrough;
      /** The size of the next filename section of the stream. */
      int64_t nxtfilenamesze;
      /** The basic encoded blocks of the next file size descriptor in the stream. */
      unsigned char nxtfilenamesze_encoded[8];
      /** The size of the file stream section of the stream. */
      int64_t nxtfilestreamsze;
      /** The basic encoded blocks of the next file stream size descriptor in the stream. */
      unsigned char nxtfilestreamsze_encoded[8];
      /** The file name of the next file to be written in the stream. */
      char *nxtfilename;
};

#endif
